package com.lottery.ruok.lottrey.dialog;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lottery.ruok.lottrey.R;
import com.lottery.ruok.lottrey.activity.BetListActivity;
import com.lottery.ruok.lottrey.eventbusObject.ModifyBetOrder;
import com.lottery.ruok.lottrey.fragment.BaseFragment;
import com.nex3z.flowlayout.FlowLayout;

import org.greenrobot.eventbus.EventBus;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import utils.Utils;

/**
 * Created by ASUS on 2017/8/2.
 */

public class OrderSetDialog extends BaseFragment{
    @BindView(R.id.line)
    SeekBar line;
    @BindView(R.id.odds)
    FlowLayout odds;
    @BindView(R.id.return_profit)
    TextView return_profit;
    @BindView(R.id.single_price)
    EditText single_price;
    @BindView(R.id.total)
    TextView total;
    @BindView(R.id.num)
    TextView num;
    @BindView(R.id.descp)
    TextView descp;
    @BindView(R.id.yuan)
    TextView yuan;
    @BindView(R.id.jiao)
    TextView jiao;
    @BindView(R.id.fen)
    TextView fen;
    @BindView(R.id.close)
    ImageView close;

    private float min_rakeback;
    private float max_rakeback;
    private LinkedHashMap max_odds;
    private LinkedHashMap theory_odds;
    private String now_rakeback;
    private float max_profit;
    private String min_profit;
    private ArrayList<TextView> oddTextView = new ArrayList<>();
    private ArrayList<String> oddNumber = new ArrayList<>();
    private float moneyPerStack = 2;
    private float unit = 1;
    private int mType = 0;

    @OnClick(R.id.confirm)
    public void confirm(){
        if(mType == 0) {
            Intent intent = new Intent(getActivity(), BetListActivity.class);
            intent.putExtra("status2", getArguments().getString("status2"));
            intent.putExtra("result", getArguments().getString("result"));
            intent.putExtra("name", getArguments().getString("name"));
            intent.putExtra("num", getArguments().getInt("num"));
            intent.putExtra("money", moneyPerStack * unit * getArguments().getInt("num"));
            intent.putExtra("no", getArguments().getLong("no"));
            intent.putExtra("code", getArguments().getString("code"));
            intent.putExtra("rule_id", getArguments().getString("rule_id"));
            intent.putExtra("checkBoxString", getArguments().getString("checkBoxString"));
            intent.putExtra("layout_code", getArguments().getString("layout_code"));
            intent.putExtra("rakeback", now_rakeback);
            StringBuilder now_odds = null;
            for (int s = 0; s < oddNumber.size(); s++) {
                if (s == 0) {
                    now_odds = new StringBuilder(oddNumber.get(s));
                } else {
                    now_odds.append(",").append(oddNumber.get(s));
                }
            }
            if(now_odds != null) {
                intent.putExtra("odds", now_odds.toString());
            }
            intent.putExtra("amount_per_note", moneyPerStack * unit);
            intent.putExtra("shopping_car", false);//是否是购物车逻辑进入
            intent.putExtra("object", getArguments().getSerializable("object"));
            intent.putExtra("getNumber_format", getArguments().getString("getNumber_format"));
            intent.putExtra("getNumber_range", getArguments().getString("getNumber_range"));
            intent.putExtra("getNumber_repeat", getArguments().getString("getNumber_repeat"));

            Gson gson = new Gson();
            String list1 = gson.toJson(max_odds);
            String list2 = gson.toJson(theory_odds);
            intent.putExtra("max_rakeback", max_rakeback);
            intent.putExtra("max_odds", list1);
            intent.putExtra("theory_odds", list2);
            intent.putExtra("max_profit", max_profit);
            intent.putExtra("min_profit", min_profit);
            intent.putExtra("min_rakeback", min_rakeback);
            startActivityForResult(intent, 1000);
        } else if(mType == 1){//返回注单页面
            ModifyBetOrder modifyBetOrder = new ModifyBetOrder();
            modifyBetOrder.setPosition(getArguments().getInt("position", 0));
            StringBuilder now_odds = null;
            for (int s = 0; s < oddNumber.size(); s++) {
                if (s == 0) {
                    now_odds = new StringBuilder(oddNumber.get(s));
                } else {
                    now_odds.append(",").append(oddNumber.get(s));
                }
            }
            if(now_odds != null) {
                modifyBetOrder.setOdds(now_odds.toString());
            }
            modifyBetOrder.setMoney(moneyPerStack * unit * getArguments().getInt("num"));
            modifyBetOrder.setRakeBack(now_rakeback);
            modifyBetOrder.setAmount_per_note(moneyPerStack * unit);

            EventBus.getDefault().post(modifyBetOrder);

            getFragmentManager().popBackStack();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == 1000){
            getActivity().getSupportFragmentManager().popBackStack();
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.dialog_order_layout, null);

        ButterKnife.bind(this, v);

        init();

        return v;
    }

    private void setYuan(){
        yuan.setBackgroundResource(R.drawable.bg_corners_8);
        jiao.setBackgroundResource(R.drawable.bg_corners_21);
        fen.setBackgroundResource(R.drawable.bg_corners_21);
        yuan.setTextColor(Color.parseColor("#ffffff"));
        jiao.setTextColor(Color.parseColor("#661dac"));
        fen.setTextColor(Color.parseColor("#661dac"));
    }

    private void setJiao(){
        yuan.setBackgroundResource(R.drawable.bg_corners_21);
        jiao.setBackgroundResource(R.drawable.bg_corners_8);
        fen.setBackgroundResource(R.drawable.bg_corners_21);
        yuan.setTextColor(Color.parseColor("#661dac"));
        jiao.setTextColor(Color.parseColor("#ffffff"));
        fen.setTextColor(Color.parseColor("#661dac"));
    }

    private void setFen(){
        yuan.setBackgroundResource(R.drawable.bg_corners_21);
        jiao.setBackgroundResource(R.drawable.bg_corners_21);
        fen.setBackgroundResource(R.drawable.bg_corners_8);
        yuan.setTextColor(Color.parseColor("#661dac"));
        jiao.setTextColor(Color.parseColor("#661dac"));
        fen.setTextColor(Color.parseColor("#ffffff"));
    }

    private void changeUnit(float a){
        unit = a;

        float money = getArguments().getInt("num") * moneyPerStack * unit;
        BigDecimal b = new BigDecimal(money);
        total.setText(Utils.saveTwoFormat(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "元");

        setDescp();
    }

    private void init(){
        String status2 = getArguments().getString("status2");
        if(status2 != null && status2.equals("0")){ //調用OrderSetDialog的入口不只一處, 別的入口不會帶 status2 (This is from NewLotteryDetailActivity)
            line.setEnabled(false);
        }
        mType = getArguments().getInt("type", 0);//0的时候是从具体彩票页面过来的，1的时候是从投注单界面过来的

        moneyPerStack = getArguments().getFloat("moneyPerStack");
        unit = getArguments().getFloat("unit");

        if(unit == 1){
            setYuan();
        } else if(unit == 0.1f){
            setJiao();
        } else if(unit == 0.01f){
            setFen();
        }

        yuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setYuan();

                changeUnit(1);
            }
        });

        jiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setJiao();

                changeUnit(0.1f);
            }
        });

        fen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                setFen();

                changeUnit(0.01f);
            }
        });

        min_rakeback = getArguments().getFloat("min_rakeback");
        max_rakeback = getArguments().getFloat("max_rakeback");
        try {
            max_odds = (LinkedHashMap)getArguments().getSerializable("max_odds");
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            theory_odds = (LinkedHashMap)getArguments().getSerializable("theory_odds");
        } catch (Exception e) {
            e.printStackTrace();
        }
        max_profit = getArguments().getFloat("max_profit");
        min_profit = getArguments().getString("min_profit");

        int r = 0;
        if(max_odds != null) {
            for (Object key : max_odds.keySet()) {
                TextView textView = new TextView(getContext());
                if (r == 0) {
                    textView.setText(max_odds.get(key).toString());
                } else {
                    textView.setText("|" + max_odds.get(key).toString());
                }
                textView.setTextColor(getResources().getColor(R.color.purples));
                textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 14);
                odds.addView(textView);
                oddTextView.add(textView);
                oddNumber.add(String.format("%.3f", Float.parseFloat(max_odds.get(key).toString())));
                r++;
            }
        }

        return_profit.setText(min_rakeback + "%");
        now_rakeback = min_rakeback + "";

        if(moneyPerStack != 0) {
            single_price.setText(Utils.saveTwoFormat(moneyPerStack));
        }

        num.setText(getArguments().getInt("num") + "");

        float money = getArguments().getInt("num") * moneyPerStack * unit;
        BigDecimal b = new BigDecimal(money);
        total.setText(Utils.saveTwoFormat(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "元");

        float max_odd = 0;
        for(String s : oddNumber){
            if(max_odd < Float.parseFloat(s)){
                max_odd = Float.parseFloat(s);
            }
        }

        float money1 = moneyPerStack * max_odd * unit;
        BigDecimal b1 = new BigDecimal(money1);
        descp.setText(b1.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "元");

        line.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                now_rakeback = String.format("%.1f", (min_rakeback + (max_rakeback - min_rakeback)*i/100.0));

                float site_profit;
                if(min_profit == null){
                    site_profit = max_profit;
                } else {
                    site_profit = max_profit - (max_profit - Float.parseFloat(min_profit)) * (Float.parseFloat(now_rakeback) / (max_rakeback - min_rakeback));
                }
                int r = 0;
                if(theory_odds != null) {
                    for (Object th : theory_odds.keySet()) {
                        float nows = Float.parseFloat(theory_odds.get(th).toString()) * (1 - site_profit / 100.0f - Float.parseFloat(now_rakeback) / 100.0f);
                        if (r == 0) {
                            oddTextView.get(r).setText(String.format("%.3f", nows));
                        } else {
                            oddTextView.get(r).setText("|" + String.format("%.3f", nows));
                        }
                        oddNumber.set(r, String.format("%.3f", nows));
                        r++;
                    }
                }

                return_profit.setText(now_rakeback + "%");

                setDescp();
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

        single_price.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(single_price.getText().toString().equals("")){
                    moneyPerStack = 0;
                } else {
                    moneyPerStack = Float.parseFloat(single_price.getText().toString());
                }

                float money = getArguments().getInt("num") * moneyPerStack * unit;
                BigDecimal b = new BigDecimal(money);
                total.setText(Utils.saveTwoFormat(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) + "元");

                setDescp();
            }
        });

        close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                getFragmentManager().popBackStack();
            }
        });
    }

    private void setDescp(){
        float max_odd = 0;
        for(String s : oddNumber){
            if(max_odd < Float.parseFloat(s)){
                max_odd = Float.parseFloat(s);
            }
        }
        float money = moneyPerStack * max_odd * unit;
        BigDecimal b = new BigDecimal(money);
        descp.setText(b.setScale(2, BigDecimal.ROUND_HALF_UP).toString() + "元");
    }
}